package cn.hls.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.swing.text.html.HTMLDocument.HTMLReader.ParagraphAction;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.hls.dao.PersonDao;
import cn.hls.entity.Person;
import cn.hls.entity.vo.PageInfo;

/**
 * @fileName: PersonDaoImpl.java
 * @package: com.bangni.dao.impl
 * @Description: 人员信息Dao接口实现类
 * @author: yinghui.zhang
 * @email: uuhui@163.com
 * @date: 2015-5-1
 */
@Component("personDaoImpl")
public class PersonDaoImpl extends BaseDaoImpl<Person> implements PersonDao {

	@Override
	public PageInfo<Person> loadPersonInfo(Person entity, PageInfo<Person> page)
			throws Exception {
		// 定义查询Hql语句
		StringBuilder selectHql = new StringBuilder();
		// 定义汇总Hql语句
		StringBuilder countHql = new StringBuilder();
		// 定义查询条件语句
		StringBuilder conditionSql = new StringBuilder();
		// 定义查询参数
		List<Object> paramList = new ArrayList<Object>();
		selectHql.append("from Person p left join fetch p.user u ");
		selectHql.append("left join fetch p.org o where p.deleted=? ");
		countHql.append("select count(p.id) from Person p left join  p.org o where p.deleted=? ");
		paramList.add(false);
		// 存在查询条件
		if (entity != null) {
			// 存在用户名称
			if (StringUtils.hasText(entity.getName())) {
				conditionSql.append("and p.name like ? ");
				paramList.add("%" + entity.getName() + "%");
			}
			// 按登录账号查询
			
			if (entity.getUser()!=null&& StringUtils.hasText(entity.getUser().getLoginName())) {
				conditionSql.append("and p.user.loginName like ?");
				paramList.add("%" + entity.getUser().getLoginName() + "%");
			}
			if(entity.getCompanyId()!=null){//根据企业编号过滤
				conditionSql.append("and p.companyId=? ");
				paramList.add(entity.getCompanyId());
			}
			if(entity.getOrg()!=null && entity.getOrg().getId()!=null){
				//判断组织机构编号是否与企业单位编号相同，若不相同则按企业编号则按组织编号查询
				if(entity.getOrg().getId().longValue()>0){//选中的节点不是根结点
					if(entity.getCompanyId()==null||entity.getOrg().getId().longValue()!=entity.getCompanyId().longValue()){
						conditionSql.append("and o.id=? ");
						paramList.add(entity.getOrg().getId());
					}
				}
			}
		}
		if (conditionSql.length() > 0) {
			selectHql.append(conditionSql);
			countHql.append(conditionSql);
		}
		return find(selectHql.toString(), countHql.toString(),
				paramList.toArray(), page);
	}

}
